
unsigned char *imageP;

void loadImage(void* heapAddr, int heapLength)
{	
	imageP = (unsigned char *)heapAddr;

	int version = readWord();
	if(version != 6502) PANIC("bad image version");
	
	int headerSize = readWord();
	int endOfMemory = readWord();
	int oldBaseAddr = readWord();
	int specialObjectsOopInt = readWord();
	int lastHash = readWord();
	readWord();
	readWord();
	readWord();
	fskip(headerSize - 9*4);
	
	heapStart = (int)(imageP);  //BOGUS  objectmemory should initial these
	heapNext = heapStart;
	heapLimit = (int)heapAddr + heapLength;
	
	int delta = heapNext - oldBaseAddr;

	heapNext += endOfMemory;
	*(int*)heapNext = 2; //mark as free block
	
	specialObjectsArray = specialObjectsOopInt + delta;
	
	int objectCount = 0;
	
	// go through heap and adjust pointers
	for(int object=heapStart;;)
	{
		int header = *(int*)object; int class;
		switch(header&3){
			case 0: //3-word header
				object+=8; 
				class = *(int*)(object-4) >> 2 << 2;
				class += delta;
				*(int*)(object-4) = class | 0;
				break;
			case 1: //2-word header
				object+=4;
				class = *(int*)(object-4) >> 2 << 2;
				class += delta;
				*(int*)(object-4) = class | 1;
				break;
			case 2: //free space marker
				if(object >= heapNext) goto done;
				PANIC("unexpected free space in incrementOops");
			case 3: //1-word (compact) header
				object+=0; 
				break;
		}
		if(object >= heapNext) PANIC("went past end of heap in incrementOops");
		objectCount++;
		
		int cc = (*(int*)object >> 12) & 0x1F; 
		if(cc==6) // a float, must fix word order
		{
			int temp = *(int*)(object+4);
			*(int*)(object+4) = *(int*)(object+8);
			*(int*)(object+8) = temp;
		}
		
		int format = formatOf(object);
		if(format <= 4){ //0...4 - pointer fields
			int nWords = sizeOf(object);
			for(int j=1; j<=nWords; j++){
				int oop = slotOf(object, j);
				if( !isSmInt(oop) ) setSlotOf( object, j, oop + delta );
			}
		}else if(format >= 12){ //12...15 - compiled methods
			header = slotOf(object, 1);
			int nWords = (header>>10)&255; //number of literals
			for(int j=2; j<=nWords+1; j++){
				int oop = slotOf(object, j);
				if( !isSmInt(oop) ) setSlotOf( object, j, oop + delta );
			}
		}else if(format >= 8){ //8...11 - bytearrays and strings
		}else{
		}
		object+= (sizeOf(object)*4) + 4;
	}
	
	done:
	
	nil = slotOf(specialObjectsArray, 1);
	false = slotOf(specialObjectsArray, 2);
	true = slotOf(specialObjectsArray, 3);

	printf("Loaded %d objects.\n", objectCount);
}

int readWord()
{
	int a = *imageP++;
	int b = *imageP++;
	int c = *imageP++;
	int d = *imageP++;
	return (d<<24)|(c<<16)|(b<<8)|(a);
}

void fskip(int bytes)
{
	for(int i=0; i<bytes; i++) imageP++;
}

